package xiaolong.lian.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xiaolong.lian.dao.DocDao;
import xiaolong.lian.dao.PageDao;
import xiaolong.lian.entity.Doc;
import xiaolong.lian.entity.Page;
import xiaolong.lian.exception.CustomException;
import xiaolong.lian.service.PageService;
import xiaolong.lian.util.Auth;
import xiaolong.lian.util.Path;

import java.io.*;
import java.util.List;
import java.util.UUID;

@Service
public class PageServiceImpl implements PageService {
    @Autowired
    private PageDao pageDao;
    @Autowired
    private DocDao docDao;

    @Override
    public List<Page> getPageList(String docId, String tel) throws CustomException {
        checkDocPermission(tel, docId);
        return pageDao.getPagesByDocId(docId);
    }

    @Override
    public Page createPage(String docId, int num, String tel) throws CustomException {
        checkDocPermission(tel, docId);
        String id = UUID.randomUUID().toString().replace("-", "");
        String dir = "/doc/" + tel + "/" + docId;
        String url = dir + "/" + id + ".json";
        File file = new File(Path.getAbsolutePath(dir) + "/" + id + ".json");
        if(!file.getParentFile().exists())
            file.getParentFile().mkdirs();
        try {
            file.createNewFile();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            String defaultPageContent = "{\"version\":\"2.2.3\",\"objects\":[],\"background\":\"#fcfcfc\"}";
            writer.write(defaultPageContent);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            throw new CustomException("创建页面失败，请稍后重试");
        }
        if(pageDao.insertPage(id, docId, num, url) < 1){
            file.delete();
            throw new CustomException("创建页面失败，请稍后重试");
        }
        return new Page(id, num, url, docId);
    }

    @Override
    public void deletePage(String id, String tel) throws CustomException {
        checkPagePermission(tel, id);
        Page page = pageDao.getPageById(id);
        if(pageDao.deletePage(id, page.getPageNum(), page.getDocId()) < 1)
            throw new CustomException("删除页面失败，请稍后重试");
        File file = new File(Path.getAbsolutePath(page.getPageUrl()));
        file.delete();
    }

    @Override
    public void updatePageData(String id, String data, String tel) throws CustomException, IOException {
        checkPagePermission(tel, id);
        Page page = pageDao.getPageById(id);
        File file = new File(Path.getAbsolutePath(page.getPageUrl()));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
        writer.write(data);
        writer.flush();
        writer.close();
    }

    @Override
    public String getPageData(String id, String tel) throws CustomException, IOException {
        checkPagePermission(tel, id);
        Page page = pageDao.getPageById(id);
        File file = new File(Path.getAbsolutePath(page.getPageUrl()));
        byte[] content = new byte[(int) file.length()];
        FileInputStream inputStream = new FileInputStream(file);
        inputStream.read(content);
        inputStream.close();
        return new String(content,"UTF-8");
    }

    public void checkDocPermission(String tel, String docId) throws CustomException {
        if(Auth.permissionChecked())
            return;
        Doc doc = docDao.getDocById(docId);
        if (doc == null)
            throw new CustomException("文档不存在");
        if(!tel.equals(doc.getTel())){
            throw new CustomException("这不是您的文档，无法操作");
        }
        Auth.setPermissionChecked();
    }

    private void checkPagePermission(String tel, String pageId) throws CustomException {
        if(Auth.permissionChecked())
            return;
        String owner = pageDao.getUserTelOfPage(pageId);
        if(owner == null || owner.length() == 0)
            throw new CustomException("页面不存在");
        if(!tel.equals(owner))
            throw new CustomException("这不是您的文档，无法操作");
        Auth.setPermissionChecked();
    }
}
